angular.module('ionicApp.directive', [])

.directive('user', function() {
    return {
        restrict: 'EA',
        transclude: true,
        // independent scope in order to multiplexing as a component
        // use attr to bind outer scope
        scope: {
            userList: '=usersLink',
            method: '=usersMethod'
        },
        //require: ['^'],
        template: '<div class="list">' +
            '<div ng-repeat="userCate in userList">' +
            '<div class="item item-divider">' +
            '<p>{{userCate.cate}}</p>' +
            '</div>' +
            '<div class="item item-avatar" ng-repeat="user in userCate.users" on-hold="method.delUser(user)" ng-click="showUser(user, $index)">' +
            '<img ng-src="{{ user.avatar }}">' +
            '<h2>{{ user.name }}</h2>' +
            '<p>{{ user.phone }}</p>' +
            '</div>' +
            '</div>' +
            '</div>',
        replace: true,
        controller: function($scope, $element, $attrs, $transclude) {

            $scope.showUser = function(user, index) {
                $scope.method.showUser(user);
            }
        }
    }
})

.directive("fileread", function(uTool) {
    return {
        restrict: "A",
        scope: {
            fileread: "="
        },
        link: function($scope, $element, $attrs) {
            
            $element.bind("change", function(changeEvent) {
                // save the file, type img
                var file = changeEvent.target.files[0];

                if (!uTool.regTest(file.type, 'imgFile')) {
                    console.log("It should be a image file");
                    return false;
                }
                var reader = new FileReader();

                reader.onload = (function(f) {
                    return function(loadEvent) {
                        // file onload has finished, return the Base64 dataUrl
                        $scope.$apply(function() {
                            $scope.fileread = {
                                url: loadEvent.target.result,
                                name: f.name
                            }
                        });
                    }
                })(file);
                // parse file to Base64
                reader.readAsDataURL(file);
            });
        }
    }
})
